package service

import (
	sqlc "bgs/db/sqlc"
	"bgs/service/model"
	"bgs/util"
	"context"
)


// FetchMapOfProductAttributeDefs map of product attribute defs
func (s *ProductServiceImp) FetchMapOfProductAttributeDefs(ctx context.Context, q *sqlc.Queries, productIDs []int64) (mapOfProductAttributeDefs model.AttributeDefMapOfProduct, err error) {
	slog := util.NewContextLogger(ctx, s.slog)
	mapOfProductAttributeDefs = make(model.AttributeDefMapOfProduct)
	productAttributeKeys, err := q.ListProductAttributeKeysByProductIDs(ctx, productIDs)
	if err != nil {
		return
	}
	slog.Infof("1 获取productAttributeKey ok")

	productAttributeValues, err := q.ListProductAttributeValuesByProductIDs(ctx, productIDs)
	if err != nil {
		return
	}
	slog.Infof("2 获取productAttributeValue ok")

	
	for _, productID := range productIDs {
		var productAttributeDefs []*model.ProductAttributeDef
		filteredProductAttributeKeys := util.Filter(util.ToGenericSlice(productAttributeKeys), func(v interface{}) bool {
			pav := v.(sqlc.ProductAttributeKey)
			return pav.ProductID == productID
		})
		for _, it := range filteredProductAttributeKeys {
			pak := it.(sqlc.ProductAttributeKey)
			pavs := util.Filter(util.ToGenericSlice(productAttributeValues), func(v interface{}) bool {
				pav := v.(sqlc.ProductAttributeValue)
				return pav.ProductAttributeKeyID == pak.ID
			})
			productAttributeDefs = append(productAttributeDefs, &model.ProductAttributeDef{
				Key: pak.Name,
				Values: util.MapToString(pavs, func(v interface{}) string {
					return v.(sqlc.ProductAttributeValue).Value
				}),
			})
		}
		
		mapOfProductAttributeDefs[productID] = productAttributeDefs
	}

	slog.Infof("3 完成productAttributeDef map 组合")
	return
}